/**
 * 
 */
package com.sebscape.sebcms.pages.persistence;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.datastore.Key;
import com.sebscape.sebcms.pages.domain.Page;
import com.sebscape.sebcms.persistence.PersistenceManagerFactoryWrapper;
import com.sebscape.sebcms.persistence.action.PersistedObjectActions;
import com.sebscape.sebcms.persistence.dao.GenericDao;
import com.sebscape.sebcms.security.domain.Group;
import com.sebscape.sebcms.security.persistence.GroupDao;

/**
 * @author Stephen
 *
 */
public class PageDao extends GenericDao<Page, Long> {

	private static Log log = LogFactory.getLog(PersistedObjectActions.class);

	/**
	 * @param clazz
	 */
	public PageDao() {
		super( Page.class );
	}

	@SuppressWarnings("unchecked")
	public Page findByName( String name ){
		// load the page
		Page page = null;
		PersistenceManager pm = PersistenceManagerFactoryWrapper.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			List<Page> result = (List<Page>)pm.newQuery( persistentClass, "name=='" + name + "'" ).execute();
			if( result != null ){
				Page p = result.get( 0 );
				// load up the collections.
				if( p != null && p.getGroupKeySet() != null ){
					try {
						p.getGroupKeySet().size();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				page = pm.detachCopy( p );
			 }
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			tx.commit();
			pm.close();
		}
		// TODO: This is a hack. Because Google does not init collections, we must fetch them manually.
		// I hope to remove this in the near future.
		if( page != null ){
			// populate the groups.
			initGroups(page);
		}
		// return the page.
		return page;
	}
	
	/* (non-Javadoc)
	 * @see com.sebscape.sebcms.persistence.dao.GenericDao#load(java.io.Serializable)
	 */
	@Override
	public Page load(Long id) {
		// load the page
		Page page = null;
		PersistenceManager pm = PersistenceManagerFactoryWrapper.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			Page p = pm.getObjectById( persistentClass, id );
			log.debug("PageDao.load: at initial load, groupKeySet = " + p.getGroupKeySet() );
			// load up the collections.
			if( p != null && p.getGroupKeySet() != null ){
				try {
					log.debug("PageDao.load: Init'ing... p.getGroupKeySet().size() = " + p.getGroupKeySet().size() );
					p.getGroupKeySet().size();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			page = pm.detachCopy( p );
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			tx.commit();
			pm.close();
		}
		// TODO: This is a hack. Because Google does not init collections, we must fetch them manually.
		// I hope to remove this in the near future.
		if( page != null ){
			// populate the groups.
			initGroups(page);
		}
		// return the page.
		return page;
	}
	
	/**
	 * using the groupIdList values, fetch and set the list of Groups.
	 * @param 
	 */
	private void initGroups( Page page ){
		log.debug("PageDao: begin initGroups...");
		GroupDao dao = new GroupDao();
		if( page.getGroupKeySet() == null ){
			log.debug( "PageDao: groupKeySet was null...creating new/empty one.");
			page.setGroups( new ArrayList<Group>() );
			page.setGroupKeySet( new HashSet<Key>() );
		}
		log.debug( "PageDao: begin loop thru page.group keys size() = " + page.getGroupKeySet().size() );
		for( Key gKey: page.getGroupKeySet() ){
			log.debug( "PageDao: Loading key/id: " + gKey + " / " + gKey.getId() );
			Group g = (Group)dao.load( gKey.getId() );
			if( g != null ){ // this could happen if group was deleted.
				log.debug( "PageDao: Added group: " + g.getName() );
				page.getGroups().add( g );
			}
		}
	}
	

	/* (non-Javadoc)
	 * @see com.sebscape.sebcms.persistence.dao.GenericDao#save(java.lang.Object)
	 */
	@Override
	public Page save(Page page) {
		if( page.getGroupKeySet() == null ){
			log.debug("AT SAVE TIME...the page.groupKeySet: NULL" );
		} else {
			log.debug("AT SAVE TIME...the page.groupKeySet: " + page.getGroupKeySet().size());	    			
		}
		return super.save( page );
	}


	/* (non-Javadoc)
	 * @see com.sebscape.sebcms.persistence.dao.GenericDao#update(java.lang.Object)
	 */
	@Override
	public Page update(Page page) {
		return super.update( page );
	}

}
